<template>
  <div class="editTree">
    <div class="filter__box">
      <el-input
        class="inline-input"
        v-if="hideInp"
        placeholder="输入关键字进行过滤"
        suffix-icon="el-icon-search"
        v-model="filterText"
        clearable
      ></el-input>
    </div>
    <div class="edit-tree-toolbar">
      <div>{{ title }}</div>
      <div class="edit-btn" v-if="haveRelated">
        <i class="el-icon-success link"><span class="words"> 已关联</span></i>
        <i class="el-icon-success noLink"><span class="words"> 未关联</span></i>
      </div>
      <div class="edit-btn" v-if="!hideBtn">
        <template v-for="(i, index) in btnConfig">
          <el-button
            type="plain"
            class="btn-text-blue"
            size="mini"
            :key="index"
            v-if="showBtn(i.name)"
            :icon="i.icon"
            @click="i.methons"
            >{{ i.text }}</el-button
          >
        </template>
      </div>
    </div>
    <div class="edit-tree-content">
      <el-tree
        :class="{ isActive: draggable }"
        class="filter-tree"
        :data="treeConfig.data"
        node-key="id"
        :props="defaultProps"
        :expand-on-click-node="clickExpand"
        :default-expand-all="expandAll"
        :default-expanded-keys="defaultExpandKeys"
        highlight-current
        :show-checkbox="showCheckbox"
        :check-strictly="checkStrictly"
        :filter-node-method="filterNode"
        @check="checkClick"
        @node-click="treeNodeClick"
        :draggable="draggable"
        @node-drag-end="handleDrop"
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
        ref="tree"
      >
      <!-- <div class="custom-tree-node" slot-scope="{ node, data }"> -->
        <div class="custom-tree-node" slot-scope="{ node, data }" v-if="!haveRelated">
          <span>{{ node.label }}</span>
          <span v-if="currentNode.id === data.id && !hideBtn && data.id !== -1">
            <el-button
              type="text"
              @click.native="() => TNodeAdd(node, data)"
              class="btnIcon"
              icon="el-icon-plus"
            ></el-button>
            <el-button
              type="text"
              @click.native="() => TNodeEdit(node, data)"
              class="btnIcon"
              icon="el-icon-edit-outline"
            ></el-button>
            <el-button
              type="text"
              @click.native="() => TNodeDel(node, data)"
              class="btnIcon"
              icon="el-icon-delete"
            ></el-button>
          </span>
        </div>
        <div class="tree-node-icons" slot-scope="{ node,data }" v-else>
          <span>{{ node.label }}</span>
          <span class="relateIcons"  v-if="haveRelated&&node.level ==5">
            <i class="el-icon-success link" v-if="data.equipment !=null&&data.equipmentName !=null"></i>
            <i class="el-icon-success noLink" v-if="data.equipment ==null||data.equipmentName ==null"></i>
          </span>
        </div>
      </el-tree>
    </div>
    <dialogPublic
      :title="treeTitle"
      :show.sync="show"
      v-if="show"
      @doSubmit="doSubmit"
      @doClose="doClose"
    >
      <editForm
        :formConfig="formConfig"
        ref="editForm"
        :formData="editFormData"
      ></editForm>
    </dialogPublic>
  </div>
</template>
<script>
export default {
  props: {
    treeSetting: {
      type: Object,
      default: () => {
        return {};
      },
    },
    formData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    optionalNum: {
      type: Number,
      default: 0,
    },
    type: {
      type: String,
      default: "special",
    },
    haveRelated: {
      type: Boolean,
      default: false,
    },
    isSpecial:{
      type: Boolean,
      default: false,
    },
    haveRemark: {
      type: Boolean,
      default: false,
    },
    hideBtn: {
      type: Boolean,
      default: false,
    },
    hideInp: {
      type: Boolean,
      default: true,
    },
    /* 节点是否可被选择 */
    showCheckbox: {
      type: Boolean,
      default: false,
    },
    /* 是否遵循父子不互相关联的做法 */
    checkStrictly: {
      type: Boolean,
      default: false,
    },
    draggable: {
      type: Boolean,
      default: false,
    },
    allowDrop: {
      type: Function,
      default: () => {
        return true;
      },
    },
    allowDrag: {
      type: Function,
      default: () => {
        return true;
      },
    },
    defaultChecked: {
      type: Boolean,
      default: false,
    },
    formItemArr: {
      type: Array,
      default: () => {
        return [];
      },
    },
    filterNode: {
      type: Function,
      default: (value, data) => {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
    },
  },

  data() {
    return {
      isDraggable: false,
      filterText: "",
      searchText: "",
      title: "树标题",
      treeTitle: "",
      expandAll: false /* 是否展开所有项 */,
      treeConfig: {
        select: true,
        data: [],
      },
      btnConfig: [
        {
          name: "add",
          text: "根节点",
          icon: "el-icon-plus",
          methons: () => {
            this.add();
          },
        },
        {
          name: "edit",
          text: "编辑",
          icon: "el-icon-edit",
          methons: () => {
            this.edit();
          },
        },
        {
          name: "delete",
          text: "删除",
          icon: "el-icon-delete",
          methons: () => {
            this.delete();
          },
        },
      ],
      btnArr: [],
      defaultProps: {
        children: "children",
        label: "orgName",
      },
      currentNode: {}, //当前节点
      formConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "父节点",
            prop: "parentName",
            type: "text",
            disabled: true,
            span: 24,
          },
          {
            label: "当前节点",
            prop: "name",
            type: "text",
            span: 24,
            required: true,
          },
        ],
      },
      show: false,
      editFormData: {},
      checkedDataList: [],
      checkedNodesData: [],
      defaultExpandKeys: [],
      remarkItem: {
        label: "备注",
        prop: "remark",
        type: "text",
        span: 24,
      },
    };
  },
  created() {
    this.init();
  },
  watch: {
    treeSetting: {
      handler(val) {
        this.$set(this.treeConfig, "data", val.data);
      },
      deep: true,
    },
    formData: {
      handler(val) {
        this.editFormData = this.formData;
      },
      deep: true,
    },
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    init() {
      let { btnArr, title, data, defaultProps, clickExpand, expandAll } =
        this.treeSetting;
      this.btnArr = btnArr || [];
      this.clickExpand = clickExpand || false; //是否点击节点展开
      this.expandAll = expandAll; //是否展开所有节点
      this.defaultProps = Object.assign({}, this.defaultProps, defaultProps);
      this.title = title || "";
      this.$set(this.treeConfig, "data", data || []);
      this.editFormData = this.formData;
      this.$set(this.formConfig, "itemArr", this.formItemArr || []);
      if (this.haveRemark) {
        this.formConfig.itemArr.push(this.remarkItem);
      }
    },
    //筛选树
    // filterNode(value, data) {
    //   if (!value) return true;
    //   return data.name.indexOf(value) !== -1;
    // },
    //显示按钮
    showBtn(btn) {
      return this.btnArr.indexOf(btn) != -1;
    },
    //点击新增
    add() {
      let data = {};
      this.show = true;
      this.treeTitle = "添加根节点";
      this.editFormData = {
        name: "",
        parentName: "",
        parent: "",
        title: this.treeTitle,
      };
    },
    handleSelect(item) {
      let currentId = item.id;
      let parentArr = this.getParentNodes(this.treeLists, currentId);
      let ids = [];
      parentArr.map((item) => {
        ids.push(item.id);
      });
      this.expandKeys = ids;
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(currentId);
      });
      this.treeNodeClick(item);
    },
    querySearch(queryString, cb) {
      let allTreeData = this.treeData;
      //新增
      let treeList = allTreeData;
      this.treeLists = allTreeData;
      let arr = treeList || [];
      let navArr = [];
      const f = function (arr) {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i];
          let children = item.children;
          if (children && children.length) {
            f(children);
          } else {
            navArr.push({
              value: item.classifyName,
              ...item,
            });
          }
        }
      };
      f(arr);
      this.navList = [...navArr];
      let restaurants = [...this.navList];
      var results = queryString
        ? restaurants.filter(this.createStateFilter(queryString))
        : restaurants;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 500 * Math.random());
    },
    //点击编辑
    edit(node) {},
    //点击删除
    delete() {},
    //返回树信息
    getFormData() {
      let { data } = this.treeConfig;
      data.map((i) => delete i.rowIndex);
      return data;
    },
    //点击树
    treeNodeClick(node) {
      this.currentNode = JSON.parse(JSON.stringify(node));
      this.$refs.tree.setCurrentKey(node.id);
      this.$emit("handleClickTree", node);
    },
    //点击复选框时触发
    async checkClick(data, checked) {
      let checkedArr = checked.checkedKeys;
      if (this.optionalNum != 0) {
        if (checkedArr.length > this.optionalNum) {
          this.$message.warning(
            "选择的节点树不得大于限定数量" + this.optionalNum + "个！"
          );
          checkedArr = await this.arrRemove(checkedArr, data.id);
          this.$refs.tree.setCheckedKeys(checkedArr);
        }
      }
    },
    arrRemove(arr, key) {
      let resArr = [];
      arr.map((i) => {
        if (i != key) {
          resArr.push(i);
        }
      });
      return resArr;
    },

    //确定
    doSubmit() {
      this.$refs.editForm.getFormData().then((res) => {
        this.$emit("save", res);
      });
    },
    //关闭
    doClose() {
      this.show = false;
    },
    //新增字节点
    TNodeAdd(node, data) {
      this.show = true;
      this.treeTitle = "添加节点";
      let { id, name } = data;
      this.editFormData = {
        name: "",
        parentName: name,
        parent: id,
        title: this.treeTitle,
      };
    },
    //编辑
    TNodeEdit(node, data) {
      this.show = true;
      this.treeTitle = "编辑节点";
      data.parentName = node.parent.data.name;
      data.sort = data.order;
      data.title = this.treeTitle;
      this.$emit("edit", data);
    },
    //删除
    TNodeDel(node, data) {
      this.$confirm("此操作将删除【" + data.name + "】, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$emit("delete", data.id);
        })
        .catch((e) => {});
    },
    setNoNode() {
      this.$refs.tree.setCurrentKey(null);
      this.currentNode = {};
    },
    getCurrentKey() {
      return this.$refs.tree.getCurrentKey();
    },
    //设置树数据
    setTreeData(data) {
      this.$set(this.treeConfig, "data", data);
      if(!this.isSpecial){
        setTimeout(() => {
        let node = {};
        if (data.length) {
          let dataArr = this.$utils.convert_tree_data(data);
          let obj = dataArr.find((i) => i.id == this.currentNode.id);
          node = obj ? this.currentNode : data[0];
        }
        this.$refs.tree.setCurrentKey(node.id);
        this.treeNodeClick(node);
      }, 0);
      }
    },
    setData(data) {
      this.$set(this.treeConfig, "data", data);
    },
    setCurrentNode(node) {
      let dataId = node.id || null;
      if (dataId) {
        this.defaultExpandKeys.length = 0;
        this.$nextTick(() => {
          this.currentNode = node;
          this.defaultExpandKeys.push(node.id);
          this.$refs.tree.setCurrentKey(node.id);
        });
      } else {
        this.currentNode = {};
      }
    },
    setCurrentKey(id) {
      this.$nextTick(() => {
        this.defaultExpandKeys.push(id);
        this.$refs.tree.setCurrentKey(id);
      });
    },
    handleDrop(draggingNode, dropNode, dropType) {
      const data = {
        id: draggingNode.key,
        targetId: dropNode.key,
        position: dropType,
      };
      this.$emit("dropNode", data);
    },
    //关闭弹窗
    choseDialog() {
      this.show = false;
    },
    //获取选中的node的Keys，用于菜单权限控制
    getCheckedKeys() {
      let halfData = this.$refs.tree.getHalfCheckedKeys(); //半选中状态的节点
      let checkedDataObj = this.$refs.tree.getCheckedNodes(); //全选中状态的节点
      let checkedData = checkedDataObj.map((i) => {
        return i.id;
      });
      let data = halfData.concat(checkedData); //合并两个数组
      return data;
    },
    getCheckedNodes() {
      let checkedDataObj = this.$refs.tree.getCheckedNodes(); //全选中状态的节点
      return checkedDataObj;
    },
  },
};
</script>
<style>
.editTree
  .el-tree--highlight-current
  .el-tree-node.is-current
  > .el-tree-node__content {
  /* background-color: #bedaf9 !important; */
}
</style>
<style lang="less" scoped>
.el-tree-node__expand-icon + .custom-tree-node {
  font-weight: 700;
}
.is-leaf + .custom-tree-node {
  font-weight: 400;
}
.editTree {
  //border: 1px solid #e1e1e1;
  padding-top: 15px;
  width: 100%;
  height: 100%;
  .edit-tree-content {
    height: calc(100% - 65px);
    overflow-y: auto;
    overflow-x: auto;
  }
  .filter__box {
    //margin-top: 15px;
    border: 0px;
    //border-bottom: 10px solid #F2F3F8;
    width: 100%;
    .inline-input {
      width: 100%;
    }
  }
}

.isActive {
  background-color: #D5E4FD;
}

.edit-tree-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
}
.link {
  color: @kr-elementUI-color;
  font-size: 14px;
  //padding: 0 10px;
}
.noLink {
  color: #d7d7d7;
  font-size: 14px;
}
.words {
  color: #666;
  padding-right: 10px;
}
.relateIcons {
  padding-left: 3px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
/* /deep/.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content>.el-tree-node__expand-icon{
    color:@kr-white-color;
}
/deep/.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content>.el-tree-node__expand-icon.is-leaf{
  color: transparent;
} */
</style>